/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Entidades;

/**
 *
 * @author usuario
 */
import DAO.ResourcesDAO;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.swing.JOptionPane;


public class SFTPFileCopy1 {
    
ResourcesDAO resource;
 

    public String retornarRuta(boolean upload, String sourcePath,  ByteArrayInputStream fileStream, String nombreObj) throws FileNotFoundException, IOException {
        
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
        String destPath = "";
        String pathMake = "";
        SftpATTRS attrs=null;
        try {
            List<ResourceEnt> lstReso;
            resource = new ResourcesDAO();
            lstReso = resource.busquedaResources();
            String usuario = "";
            String contrasenha = "";
            String direccion = "";
            
            for (ResourceEnt res : lstReso) {

                if(res.getClave().trim().equals("USUARIO_FTP")){
                     usuario = res.getValor().trim();
                 }
                if(res.getClave().trim().equals("CLAVE_FTP")){
                     contrasenha = res.getValor().trim();
                 }
                if(res.getClave().trim().equals("DIRECCION_FTP")){
                     direccion = res.getValor().trim();
                 }
                
                if(res.getClave().trim().equals("DIRECTORIO_FTP")){
                     destPath = res.getValor().trim();
                 }
                
                
            } 
            pathMake = destPath + nombreObj.replaceAll(" ", "_");
            destPath = pathMake + "/"+  sourcePath;
           
            JSch jsch = new JSch();
            //jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
            session = jsch.getSession(usuario, direccion, 22);
            session.setPassword(contrasenha);

            UserInfo ui = new MyUserInfo() {
                public void showMessage(String message) {

                    JOptionPane.showMessageDialog(null, message);

                }

                public boolean promptYesNo(String message) {

                    Object[] options = {"yes", "no"};

                    int foo = JOptionPane.showOptionDialog(null,
                            message,
                            "Warning",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE,
                            null, options, options[0]);

                    return foo == 0;

                }
            };
            session.setUserInfo(ui);

            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            sftpChannel = (ChannelSftp) channel;
            
            
            try {
                 attrs = sftpChannel.stat(pathMake);
            } catch (Exception e) {
                
            }   
            
            if (attrs == null) {
                
                sftpChannel.mkdir(pathMake);
            }
            
            if (upload) { // File upload.

                sftpChannel.put(fileStream, destPath);
                fileStream.close();
                
            } else { // File download.
                byte[] buffer = new byte[1024];
                BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));
                OutputStream os = new FileOutputStream(new File(destPath));
                BufferedOutputStream bos = new BufferedOutputStream(os);
                int readCount;
                while ((readCount = bis.read(buffer)) > 0) {
                    bos.write(buffer, 0, readCount);
                }
                bis.close();
                bos.close();
            }
        } catch (Exception e) {
            System.out.println(e);
            destPath = "null";
        } finally {
            if (sftpChannel != null) {
                sftpChannel.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
        return destPath;
            
    }
    
    
        public String retornarRutaDownload(String sourcePath) throws FileNotFoundException, IOException {
        
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
        String destPath = "";
        File source = new File(sourcePath);
        destPath =  source.getName();
        
        try {
            List<ResourceEnt> lstReso;
            resource = new ResourcesDAO();
            lstReso = resource.busquedaResources();
            String usuario = "";
            String contrasenha = "";
            String direccion = "";
            
            for (ResourceEnt res : lstReso) {

                if(res.getClave().trim().equals("USUARIO_FTP")){
                     usuario = res.getValor().trim();
                 }
                if(res.getClave().trim().equals("CLAVE_FTP")){
                     contrasenha = res.getValor().trim();
                 }
                if(res.getClave().trim().equals("DIRECCION_FTP")){
                     direccion = res.getValor().trim();
                 }
                
                
                
            } 
            
            JSch jsch = new JSch();
            //jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
            session = jsch.getSession(usuario, direccion, 22);
            session.setPassword(contrasenha);

            UserInfo ui = new MyUserInfo() {
                public void showMessage(String message) {

                    JOptionPane.showMessageDialog(null, message);

                }

                public boolean promptYesNo(String message) {

                    Object[] options = {"yes", "no"};

                    int foo = JOptionPane.showOptionDialog(null,
                            message,
                            "Warning",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE,
                            null, options, options[0]);

                    return foo == 0;

                }
            };
            session.setUserInfo(ui);

            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            sftpChannel = (ChannelSftp) channel;

            byte[] buffer = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));
            OutputStream os = new FileOutputStream(new File(destPath));
            BufferedOutputStream bos = new BufferedOutputStream(os);
            int readCount;
            while ((readCount = bis.read(buffer)) > 0) {
                bos.write(buffer, 0, readCount);
            }
            bis.close();
            bos.close();
            
        } catch (Exception e) {
            System.out.println(e);
            destPath = "null";
        } finally {
            if (sftpChannel != null) {
                sftpChannel.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
        return destPath;
            
    }
        
        
    public String deleteFile(String sourcePath) throws FileNotFoundException, IOException {
        
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
        String eliminado = "0";

        
        try {
            List<ResourceEnt> lstReso;
            resource = new ResourcesDAO();
            lstReso = resource.busquedaResources();
            String usuario = "";
            String contrasenha = "";
            String direccion = "";
            
            
            for (ResourceEnt res : lstReso) {

                if(res.getClave().trim().equals("USUARIO_FTP")){
                     usuario = res.getValor().trim();
                 }
                if(res.getClave().trim().equals("CLAVE_FTP")){
                     contrasenha = res.getValor().trim();
                 }
                if(res.getClave().trim().equals("DIRECCION_FTP")){
                     direccion = res.getValor().trim();
                 }
                
                
                
            } 
            
            JSch jsch = new JSch();
            //jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
            session = jsch.getSession(usuario, direccion, 22);
            session.setPassword(contrasenha);

            UserInfo ui = new MyUserInfo() {
                public void showMessage(String message) {

                    JOptionPane.showMessageDialog(null, message);

                }

                public boolean promptYesNo(String message) {

                    Object[] options = {"yes", "no"};

                    int foo = JOptionPane.showOptionDialog(null,
                            message,
                            "Warning",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE,
                            null, options, options[0]);

                    return foo == 0;

                }
            };
            session.setUserInfo(ui);

            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            sftpChannel = (ChannelSftp) channel;

            sftpChannel.rm(sourcePath.trim());
            eliminado = "1";
        } catch (Exception e) {
            System.out.println(e);
            eliminado = "0";
            
        } finally {
            if (sftpChannel != null) {
                sftpChannel.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
        return eliminado;
            
    }

    public static abstract class MyUserInfo
            implements UserInfo, UIKeyboardInteractive {

        public String getPassword() {
            return null;
        }

        public boolean promptYesNo(String str) {
            return false;
        }

        public String getPassphrase() {
            return null;
        }

        public boolean promptPassphrase(String message) {
            return false;
        }

        public boolean promptPassword(String message) {
            return false;
        }

        public void showMessage(String message) {
        }

        public String[] promptKeyboardInteractive(String destination,
                String name,
                String instruction,
                String[] prompt,
                boolean[] echo) {

            return null;
        }
    }
}